<template>
  <div>
    <!-- 个人中心主体内容 -->
    <div class="container mt-4">
      <h2 class="mb-4">个人中心</h2>

      <div class="row">
        <!-- 基本信息展示与编辑 -->
        <div class="col-md-7 mb-4">
          <div class="card">
            <div class="card-header">基本信息</div>
            <div class="card-body">
              <form @submit.prevent="saveProfile">
                <div class="mb-3 row">
                  <label for="username" class="col-sm-3 col-form-label">用户名:</label>
                  <div class="col-sm-9">
                    <input
                      type="text"
                      readonly
                      class="form-control-plaintext"
                      id="username"
                      :value="currentUser.username"
                    />
                  </div>
                </div>
                <div class="mb-3 row">
                  <label for="name" class="col-sm-3 col-form-label">姓名:</label>
                  <div class="col-sm-9">
                    <input type="text" class="form-control" id="name" v-model="editableUser.name" />
                  </div>
                </div>
                <div class="mb-3 row">
                  <label for="role" class="col-sm-3 col-form-label">角色:</label>
                  <div class="col-sm-9">
                    <input
                      type="text"
                      readonly
                      class="form-control-plaintext"
                      id="role"
                      :value="currentUser.role"
                    />
                  </div>
                </div>
                <div class="mb-3 row">
                  <label for="department" class="col-sm-3 col-form-label">所属部门:</label>
                  <div class="col-sm-9">
                    <input
                      type="text"
                      class="form-control"
                      id="department"
                      v-model="editableUser.department"
                    />
                  </div>
                </div>
                <div class="mb-3 row">
                  <label for="email" class="col-sm-3 col-form-label">邮箱:</label>
                  <div class="col-sm-9">
                    <input
                      type="email"
                      class="form-control"
                      id="email"
                      v-model="editableUser.email"
                    />
                  </div>
                </div>
                <div class="mb-3 row">
                  <label for="phone" class="col-sm-3 col-form-label">联系电话:</label>
                  <div class="col-sm-9">
                    <input
                      type="tel"
                      class="form-control"
                      id="phone"
                      v-model="editableUser.phone"
                    />
                  </div>
                </div>
              </form>
            </div>
          </div>
        </div>

        <!-- 账户安全/修改密码 -->
        <div class="col-md-5 mb-4">
          <div class="card">
            <div class="card-header">账户安全</div>
            <div class="card-body">
              <form @submit.prevent="changePassword">
                <div class="mb-3">
                  <label for="currentPassword" class="form-label">当前密码:</label>
                  <input
                    type="password"
                    class="form-control"
                    id="currentPassword"
                    v-model="passwordForm.currentPassword"
                    required
                  />
                </div>
                <div class="mb-3">
                  <label for="newPassword" class="form-label">新密码:</label>
                  <input
                    type="password"
                    class="form-control"
                    id="newPassword"
                    v-model="passwordForm.newPassword"
                    required
                  />
                </div>
                <div class="mb-3">
                  <label for="confirmPassword" class="form-label">确认新密码:</label>
                  <input
                    type="password"
                    class="form-control"
                    id="confirmPassword"
                    v-model="passwordForm.confirmPassword"
                    required
                  />
                  <div
                    v-if="
                      passwordForm.newPassword !== passwordForm.confirmPassword &&
                      passwordForm.confirmPassword
                    "
                    class="text-danger small mt-1"
                  >
                    两次输入的密码不一致。
                  </div>
                </div>
                <div class="d-flex justify-content-end">
                  <button
                    type="submit"
                    class="btn btn-warning"
                    :disabled="
                      passwordForm.newPassword !== passwordForm.confirmPassword ||
                      !passwordForm.newPassword
                    "
                  >
                    修改密码
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 导入api实例，以便后续的“保存更改”和“修改密码”功能可以使用
import api from '@/utils/api.js';

export default {
  name: 'PersonalCenter',
  data() {
    return {
      // navItems 数据保持不变
      navItems: [
        { text: '首页', href: '#home' },
        { text: '分组管理', href: '#group' },
        { text: '消息发送中心', href: '#message' },
        { text: '事务处理', href: '#tasks' },
        { text: '阅后即焚', href: '#burn' },
      ],
      // 【修改1】: 将 currentUser 和 editableUser 初始化为空对象
      currentUser: {},
      editableUser: {},
      // 修改密码表单保持不变
      passwordForm: {
        currentPassword: '',
        newPassword: '',
        confirmPassword: '',
      },
    }
  },
  // 【修改2】: 在 created 生命周期钩子中调用加载数据的方法
  created() {
    this.loadUserInfoFromCache();
  },
  methods: {
    // 【修改3】: 新增一个专门用于从缓存加载数据的方法
    loadUserInfoFromCache() {
      const storedUserInfo = localStorage.getItem('userInfo');

      if (storedUserInfo) {
        // 如果成功从缓存中读取到数据
        console.log("成功从localStorage加载用户信息:", storedUserInfo);

        // 将JSON字符串解析回JavaScript对象
        const userInfoObject = JSON.parse(storedUserInfo);

        // 将解析出的真实用户数据赋值给 currentUser
        // 注意：我们将后端的 account 字段映射到页面的 username 显示
        this.currentUser = {
            userId: userInfoObject.userId,
            username: userInfoObject.account, // <--- 关键映射
            name: userInfoObject.name,
            role: userInfoObject.role,
            department: userInfoObject.department,
            email: userInfoObject.email,
            phone: userInfoObject.phone,
        };

        // 为可编辑的表单数据创建一个深拷贝副本
        this.editableUser = JSON.parse(JSON.stringify(this.currentUser));

      } else {
        // 如果缓存中没有用户信息，提示并跳转到登录页
        alert('未找到登录信息，请重新登录！');
        this.$router.push('/login');
      }
    },

    // 【修改4】: 更新 saveProfile 方法以使用真实API
    async saveProfile() {
      // 准备要发送到后端的数据。后端需要TUser的字段名。
      const userDataToSave = {
          userId: this.currentUser.userId, // userId是必须的
          name: this.editableUser.name,
          department: this.editableUser.department,
          email: this.editableUser.email,
          phone: this.editableUser.phone,
      };

      try {
        const response = await api.put('/personal_center/profile', userDataToSave);
        if (response.data.code === 1) {
          alert('个人信息更新成功！');
          // 更新成功后，需要同时更新缓存和当前页面显示的数据
          this.currentUser.name = this.editableUser.name;
          this.currentUser.department = this.editableUser.department;
          this.currentUser.email = this.editableUser.email;
          this.currentUser.phone = this.editableUser.phone;
          // 将 currentUser 映射回 localStorage 所需的 userInfo 格式
          const updatedUserInfo = { ...JSON.parse(localStorage.getItem('userInfo')), ...this.currentUser };
          localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo));
        } else {
          alert('保存失败：' + response.data.msg);
        }
      } catch (error) {
        console.error("保存个人信息时出错:", error);
        alert('网络错误，保存失败！');
      }
    },

    // 【修改5】: 更新 changePassword 方法以使用真实API
    async changePassword() {
      if (this.passwordForm.newPassword !== this.passwordForm.confirmPassword) {
        alert('新密码与确认密码不一致！');
        return;
      }
      try {
        const response = await api.post('/personal_center/password', {
            currentPassword: this.passwordForm.currentPassword,
            newPassword: this.passwordForm.newPassword
        });
        if (response.data.code === 1) {
          alert('密码修改成功！');
          this.passwordForm.currentPassword = '';
          this.passwordForm.newPassword = '';
          this.passwordForm.confirmPassword = '';
        } else {
          alert('密码修改失败：' + response.data.msg);
        }
      } catch (error) {
        console.error("修改密码时出错:", error);
        alert('网络错误，修改密码失败！');
      }
    },

    // goToHome 方法保持不变
    goToHome() {
      this.$router.push('/');
    },
  },
}
</script>

<style scoped>
/* 如果需要，可以在这里添加特定于此页面的样式 */
.card-header {
  background-color: #f8f9fa; /* 淡灰色背景 */
  font-weight: bold;
}
.form-control-plaintext {
  padding-left: 0; /* 调整纯文本输入框的内边距，使其与标签更对齐 */
}
</style>
